import java.util.Arrays;

public class FindLongestChain {

    public int findLongestChain1(int[][] pairs) {
        Arrays.sort(pairs, (a, b) -> {
            if (a[0] != b[0]) return a[0] - b[0];
            return a[1] - b[1];
        });
        int end = pairs[0][1];
        int ans = 1;
        for (int i = 1; i < pairs.length; i++) {
            if (pairs[i][0] > end) {
                end = pairs[i][1];
                ++ans;
            } else if (pairs[i][1] < end) {
                end = pairs[i][1];
            }
        }
        return ans;
    }

    public int findLongestChain(int[][] pairs) {
        Arrays.sort(pairs, (a, b) -> a[0] - b[0]);
        int[] dp = new int[pairs.length];
        Arrays.fill(dp, 1);
        for (int i = 1; i < pairs.length; i++) {
            for (int j = 0; j < i; j++) {
                if (pairs[i][0] > pairs[j][1]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
        }
        return dp[dp.length - 1];
    }
}
